package life.system.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import life.system.common.dto.MemberResponseVo;
import life.system.common.enume.OrderStatusEnum;
import life.system.common.to.mq.OrderVo;
import life.system.common.utils.R;
import life.system.common.vo.SkuInfoVo;
import life.system.order.entity.OrderItemEntity;
import life.system.order.feign.ProductFeignService;
import life.system.order.interceptor.LoginUserInterceptor;
import life.system.order.service.OrderItemService;
import life.system.order.to.OrderCreateTo;
import life.system.order.vo.OrderDetailVo;
import life.system.order.vo.OrderListVo;
import life.system.order.vo.OrderSubmitVo;
import life.system.order.vo.SubmitOrderResponseVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import life.system.common.utils.PageUtils;
import life.system.common.utils.Query;

import life.system.order.dao.OrderDao;
import life.system.order.entity.OrderEntity;
import life.system.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Transactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo submitVo) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();

        // 1、创建订单，订单项等信息
        OrderCreateTo order = createOrder(submitVo);

        // 保存订单
        saveOrder(order);

        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());

        responseVo.setCode(0);
        responseVo.setOrder(order.getOrder());

        return responseVo;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        OrderEntity orderEntity = this.getById(entity.getId());
        if (Objects.equals(orderEntity.getStatus(), OrderStatusEnum.CREATE_NEW.getCode())) {
            // 关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);

            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(orderEntity, orderVo);
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
        return order;
    }

    @Override
    public OrderDetailVo detail(String orderSn) {

        OrderDetailVo detailVo = new OrderDetailVo();

        // 根据订单号查询订单信息
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        // 根据订单号查询订单项信息
        OrderItemEntity orderItem = orderItemService.getOne(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));

        detailVo.setOrderSn(orderSn);
        detailVo.setQcCode(order.getQcCode());
        detailVo.setCreateTime(order.getCreateTime());
        detailVo.setPaymentTime(order.getPaymentTime());
        detailVo.setSkuName(orderItem.getSkuName());
        detailVo.setSkuPic(orderItem.getSkuPic());
        detailVo.setSkuPrice(orderItem.getSkuPrice());
        detailVo.setSkuQuantity(orderItem.getSkuQuantity());
        detailVo.setTotalAmount(order.getTotalAmount());
        detailVo.setRealAmount(orderItem.getRealAmount());
        return detailVo;
    }

    @Override
    public List<OrderListVo> getOrderList() {
        String wxToken = LoginUserInterceptor.loginUser.get();
        String memberJson = (String) redisTemplate.boundHashOps("token:" + wxToken).get(wxToken);
        MemberResponseVo memberResponseVo = JSONObject.parseObject(memberJson, MemberResponseVo.class);

        // 1、查询当前用户的订单列表
        List<OrderEntity> orderEntityList = this.list(new QueryWrapper<OrderEntity>().eq("member_id", memberResponseVo.getId()).orderByDesc("create_time"));

        List<OrderListVo> orderListVos = new ArrayList<>();

        for (OrderEntity order : orderEntityList) {
            OrderListVo orderListVo = new OrderListVo();

            OrderDetailVo detail = this.detail(order.getOrderSn());

            orderListVo.setOrderSn(order.getOrderSn());
            orderListVo.setStatus(order.getStatus());
            orderListVo.setCreateTime(order.getCreateTime());
            orderListVo.setSkuName(detail.getSkuName());
            orderListVo.setSkuPic(detail.getSkuPic());
            orderListVo.setSkuQuantity(detail.getSkuQuantity());
            orderListVo.setRealAmount(detail.getRealAmount());

            orderListVos.add(orderListVo);
        }
        return orderListVos;
    }

    // 保存订单
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        OrderItemEntity orderItems = order.getOrderItems();
        orderItemService.save(orderItems);
    }

    // 创建订单
    private OrderCreateTo createOrder(OrderSubmitVo submitVo) {
        OrderCreateTo createTo = new OrderCreateTo();
        // 1、生成一个订单号
        String orderSn = IdWorker.getTimeId();
        // 创建订单
        OrderEntity orderEntity = buildOrder(orderSn,submitVo);
        // 2、获取所有的订单项
        OrderItemEntity itemEntities = buildOrderItems(orderSn,submitVo);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    private OrderItemEntity buildOrderItems(String orderSn, OrderSubmitVo submitVo) {

        R info = productFeignService.info(submitVo.getSkuId());
        SkuInfoVo data = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
        });

        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(orderSn);
        orderItemEntity.setSkuId(data.getId());
        orderItemEntity.setSkuName(data.getTitle());
        orderItemEntity.setSkuPic(data.getSkuDefaultImg());
        orderItemEntity.setSkuPrice(data.getPrice());
        orderItemEntity.setSkuQuantity(submitVo.getNum());
        orderItemEntity.setRealAmount(submitVo.getPayAmount());

        return orderItemEntity;
    }

    // 生成订单
    private OrderEntity buildOrder(String orderSn, OrderSubmitVo submitVo) {
        String wxToken = LoginUserInterceptor.loginUser.get();
        String memberJson = (String) redisTemplate.boundHashOps("token:" + wxToken).get(wxToken);
        MemberResponseVo memberResponseVo = JSONObject.parseObject(memberJson, MemberResponseVo.class);

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberResponseVo.getId());
        orderEntity.setCreateTime(new Date());
        orderEntity.setMemberUsername(memberResponseVo.getNickname());
        orderEntity.setDeleteStatus(0);
        orderEntity.setPayAmount(submitVo.getPayAmount());
        orderEntity.setTotalAmount(submitVo.getPayAmount());

        // 设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        return orderEntity;
    }


}